package com.jystudio.roc.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jystudio.roc.bean.RocDTO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.junit.Test;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

/**
 * @author sunhcug
 * @version 1.0
 * @description: TODO
 * @date 2024/1/16 10:00 PM
 */
@Service
@Slf4j
public class RocUtils {

        @Test
        public void getBaoan() {
            securityHousing("http://zjj.sz.gov.cn/ztfw/zfbz/tzgg2017/index.html");
    }


    @SneakyThrows
//    @Test
    public static List<RocDTO> securityHousing(String url) {
        List<RocDTO> list = new ArrayList<>();
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url(url)
//                .method("GET", body)
                    .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                    .addHeader("Cache-Control", "max-age=0")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Cookie", "Path=/; Path=/; Path=/; ftzjjszgovcn=0; Hm_lvt_ddaf92bcdd865fd907acdaba0285f9b1=1705405786; Path=/; arialoadData=false; nowKeyWord=29280; session-cookie=11693202; pgv_pvi=1163856896; pgv_si=s3128633344; Hm_lpvt_ddaf92bcdd865fd907acdaba0285f9b1=1705406433; Path=/")
                    .addHeader("Referer", "https://zjj.sz.gov.cn/")
                    .addHeader("Sec-Fetch-Dest", "document")
                    .addHeader("Sec-Fetch-Mode", "navigate")
                    .addHeader("Sec-Fetch-Site", "same-origin")
                    .addHeader("Sec-Fetch-User", "?1")
                    .addHeader("Upgrade-Insecure-Requests", "1")
                    .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")
                    .addHeader("sec-ch-ua", "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Google Chrome\";v=\"122\"")
                    .addHeader("sec-ch-ua-mobile", "?0")
                    .addHeader("sec-ch-ua-platform", "\"macOS\"")
                    .build();
            Response response = client.newCall(request).execute();
            String str = response.body().string();
            String p = "https://zjj.sz.gov.cn/ztfw/zfbz/tzgg2017/content/";
            String[] ss = str.split(p);
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            for (int i = 0; i < ss.length; i++) {
                String t = ss[i];
                if (t.contains("top_1") || t.contains("招标")) continue;
                String s = t.split("\"")[0];
                String[] tt = t.split("<span>");
                if (tt.length > 1) {
                    String s1 = tt[1].split("</span>")[0];
                    if (s1.length() < 9) {
                        s1 = "20" + s1;
                    }
                    if ((t.contains("配租") || t.contains("补租") || t.contains("公共租赁住房") || t.contains("选房") || t.contains("保障性租赁住房")) && !t.contains("残疾") && !t.contains("退役") && !t.contains("公司")) {
                        log.debug("s22:{},{}", s1, p + s);
                        log.debug("title:{}", t.split("title=\"")[1].split("\"")[0]);
                        String title = t.split("title=\"")[1].split("\"")[0];
                        RocDTO rocDTO = new RocDTO();
                        rocDTO.setType(1);
                        rocDTO.setDate(s1);
                        rocDTO.setCreatedAt(simpleDateFormat.parse(s1));
                        rocDTO.setTitle(title);
                        rocDTO.setUrl(p + s);
                        list.add(rocDTO);
                        log.debug("roc:{}", JSONObject.toJSONString(rocDTO));
                    } else {

                    }
                }
            }
            if (str.contains("下一页")) {
                String[] pas = str.split("下一页")[0].split("\"");
//            securityHousing(pas[pas.length - 2]);
            }
        } catch (Exception e) {
            log.error("securityHousing-error:{}", e);
        }
        return list;
    }

    @SneakyThrows
    public static void getContent(String url) {
        OkHttpClient client = new OkHttpClient().newBuilder()
                .build();
        MediaType mediaType = MediaType.parse("text/plain");
        RequestBody body = RequestBody.create(mediaType, "");
        Request request = new Request.Builder()
                .url(url)
//                .method("GET", body)
                .addHeader("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7")
                .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                .addHeader("Cache-Control", "max-age=0")
                .addHeader("Connection", "keep-alive")
                .addHeader("Cookie", "Path=/; Path=/; Path=/; Path=/; ftzjjszgovcn=0; Hm_lvt_ddaf92bcdd865fd907acdaba0285f9b1=1705405786; Path=/; arialoadData=false; nowKeyWord=29280; session-cookie=11693202; pgv_pvi=1163856896; pgv_si=s3128633344; Hm_lpvt_ddaf92bcdd865fd907acdaba0285f9b1=1705448539; Path=/; Path=/")
                .addHeader("Referer", "https://zjj.sz.gov.cn/")
                .addHeader("Sec-Fetch-Dest", "document")
                .addHeader("Sec-Fetch-Mode", "navigate")
                .addHeader("Sec-Fetch-Site", "same-origin")
                .addHeader("Sec-Fetch-User", "?1")
                .addHeader("Upgrade-Insecure-Requests", "1")
                .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")
                .addHeader("sec-ch-ua", "\"Chromium\";v=\"122\", \"Not(A:Brand\";v=\"24\", \"Google Chrome\";v=\"122\"")
                .addHeader("sec-ch-ua-mobile", "?0")
                .addHeader("sec-ch-ua-platform", "\"macOS\"")
                .build();
        Response response = client.newCall(request).execute();
        log.debug("response:{}", response.body().string());
    }

    @SneakyThrows
    public static List<RocDTO> getBaoan(int page) {
        List<RocDTO> list = new ArrayList<>();
        try {
            OkHttpClient client = new OkHttpClient().newBuilder()
                    .build();
            MediaType mediaType = MediaType.parse("text/plain");
            RequestBody body = RequestBody.create(mediaType, "");
            Request request = new Request.Builder()
                    .url("http://www.baoan.gov.cn/bajshej/gkmlpt/api/all/0?page=" + page + "&sid=755139")
//                .method("GET", body)
                    .addHeader("Accept", "application/json, text/javascript, */*; q=0.01")
                    .addHeader("Accept-Language", "zh-CN,zh;q=0.9")
                    .addHeader("Connection", "keep-alive")
                    .addHeader("Cookie", "_gscu_1745720862=054492596ant4715; _gscbrs_1745720862=1; _gscs_1745720862=05449259tfric015|pv:5; front_uc_session=eyJpdiI6IldSN2JEaFIxWnpNRDNQUUVEcm92SVE9PSIsInZhbHVlIjoidDV2djViSERabUxNQU1pRG14TU82SVQyVE9zSWlnUk8ydHdhaGpuSENQN1Ruc0NHb2lZc2lERElHb1lQaTFldiIsIm1hYyI6IjQzMjVjYTAyNDBjOThlOGMyNjNkMWRhMWY2NmYxODQxNmQzYmFmZTE3NTRjNzJmZTM5NWZjOTVkMjIxOGUzOWUifQ%3D%3D; laravel_session=eyJpdiI6IkZ0TmhHdzZCT1gyUVFKYWR2bW92THc9PSIsInZhbHVlIjoiYXBQNEg2VE9ENndqTEttdHNHUlFsaUN0VGRYRTcyazhWdmp5VDNoRHJJWnNqVU9sT2Z5dWIzd3N5WGMwWkRjSCIsIm1hYyI6ImE1N2FhMDNiOGExYjRjNTg0OGY1ZWU4ZGNmMmJkOWQwYWI3NGM2YjU5MmY0OTYwYjU0MjAxYWJhMTZjODg2MWEifQ%3D%3D; laravel_session=eyJpdiI6Ino1Wkx6XC81TU9ZamFtemhocHZlOXlnPT0iLCJ2YWx1ZSI6InRWSmZnSFlHaVBQazlCVlhiYWNcL1wvckRQTnFEU1pOQThDU2tWSTFGRnExXC90SGxQdmpcL241MjFYVFU1b0EycE5hIiwibWFjIjoiODUyMTAxNDAyYjIyODI0NGMwZWZkZjAzNGNkMjMzMWZiYjQxOTc5YjdlMDAxNWI2NzVjOTAxNWI4NjQwMGUyYSJ9")
                    .addHeader("Referer", "http://www.baoan.gov.cn/")
                    .addHeader("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36")
                    .addHeader("X-Requested-With", "XMLHttpRequest")
                    .build();
            Response response = client.newCall(request).execute();
            JSONObject jsonObject = JSONObject.parseObject(response.body().string());
            JSONArray jsonArray = jsonObject.getJSONArray("articles");
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject object = jsonArray.getJSONObject(i);
                if (object.getString("keywords").contains("在册轮候家庭") || object.getString("title").contains("选房") || object.getString("title").contains("在册轮候家庭") || object.getString("title").contains("补租") || object.getString("title").contains("配租") || object.getString("title").contains("公共租赁住房") || object.getString("title").contains("保障性租赁住房")) {
                    if (!object.getString("title").contains("退役") && !object.getString("title").contains("招标") && !object.getString("title").contains("公司")) {
                        log.debug("created_at:{}", object.get("created_at"));
                        log.debug("title:{}", object.get("title"));
                        log.debug("url:{}", object.get("url"));
                        RocDTO rocDTO = new RocDTO();
                        rocDTO.setType(2);
                        rocDTO.setDate(object.getString("created_at"));
                        rocDTO.setCreatedAt(object.getDate("created_at"));
                        rocDTO.setTitle(object.getString("title"));
                        rocDTO.setUrl(object.getString("url"));
                        list.add(rocDTO);
                    }
                }
            }
            int total = jsonObject.getInteger("total");
            int offset = jsonObject.getInteger("offset");
            if (total - 100 > offset) {
//            getBaoan(page + 1);
            }
        } catch (Exception e) {
            log.error("getBaoan error", e);
        }
        return list;
    }
}
